{% extends "mdm/basemdm.html" %}

{% block title %} {{ titulo }} {% endblock %}

{% block contenido %}
     <div id="contenido">
          <div id="todo" class="sombra ui-accordion-header ui-helper-reset ui-state-active ui-corner-all">
               <div class="demo ui-widget ui-helper-clearfix">
                    <div id="fondos" class="ui-widget-content ui-state-default">
                         <h4 class="ui-widget-header"><span>Fotos presentaci&oacute;n<button id="newfp" href="#" rel="FP">A&ntilde;adir foto</button></span></h4>
                         <ul id="FPul" class="gallery ui-helper-reset ui-helper-clearfix"></ul>
                    </div>
                    <div id="album" class="ui-widget-content ui-state-default">
                         <h4 class="ui-widget-header"><span>Galer&iacute;a de fotos</span></h4>
                         <ul id="Albm" class="gallery ui-helper-reset ui-helper-clearfix"></ul>
                    </div>
               </div>
          </div>                    
     </div>
     <div id="up_div">
          <div class="upload_div ui-dialog ui-widget ui-widget-content ui-corner-all" title="A&ntilde;adir fotos">
               <div class="ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix"><span class="ui-dialog-title" id="ui-dialog-title-1">Añadir fotos</span></div>
               <div class="c">
                    <span class="fileinput-button">
                         <span class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" style="padding: 10px;">Seleccionar fotos...</span>
                         <input id="fileupload" type="file" accept="image/png" name="files" multiple>
                    </span>
                    <br> 
                    <div id="progress" class="progress"></div>
                    <div id="files" class="files"></div>
               </div>
               <div class="ui-dialog-buttonpane ui-widget-content ui-helper-clearfix">
                    <div class="ui-dialog-buttonset"><button id="cerrarFrm" href="#">Cerrar</button></div>
               </div>
          </div>
     </div>

{% endblock  %}

{% block script %}
     <script>
     var swfu
     
     var params = {'{{session_cookie_name}}': '{{session_key}}', '{{ csrf_token_name }}': '{{ csrf_token }}'}
     $(
          function() {

               $('#newfp').button(
                    {
                         icons: {
                              primary: "ui-icon-plus"
                              },
                         text: false
                    }
               ).click(
                    function(){
                         $('#files').empty()
                         $('#progress').progressbar('value', 0);
                         $('#up_div').fadeIn()
                    }
               )
               
               $(document).on(
                    'click', 'ul.gallery > li > a',
                    function( event ) {
                         var $item = $( this ),
                              $target = $( event.target )

                         if ( $target.is( 'a.ui-icon-trash' ) ) {
                              deleteImage( $target )
                         } else if ( $target.is( 'a.ui-icon-zoomin' ) ) {
                              viewLargerImage( $target )
                         }
                         return false
                    }
               )
             
               $('#FPul').sortable(
                    {
                         tolerance: 'pointer',
                         update: 
                              function(event, ui) {
                                   reordenar(ui.item)
                              }
                    }
               ).droppable(
                    {
                         accept: 'ul#Albm li' ,
                         drop: 
                              function( event, ui ) {
                                   nuevofondo(ui.draggable)
                              }
                         }
               )
               
               $('#FPul').disableSelection()
                         
               $('#progress').progressbar();
                         
               $('#fileupload').fileupload(
                    {
                         url: '{% url "mdm.views.nuevofon" %}',
                         dataType: 'json',
                         singleFileUploads: false,
                         done: function (e, data) {
                              $.each(data.files, function (index, file) {
                                   $('<p/>').text('Imagen '+file.name+' añadida correctamente.').appendTo('#files')
                              })
                         },
                         progressall: function (e, data) {
                              $('#progress').progressbar('value', parseInt(data.loaded / data.total * 100, 10));
                         },
                         fail: function(e, data) {
                              $('<p/>').text(data.errorThrown).appendTo('#files')
                              $('<p/>').text(data.textStatus).appendTo('#files')
                         },
                         submit: function (e, data) {
                              var goUpload = true
                              for(var i=0; i<data.files.length; i++){
                                   if (!(/(\.|\/)(gif|jpe?g|png)$/i).test(data.files[i].name)) {
                                        $('<p/>').text(data.files[i].name + ': no válido. Sólo jpg o png').appendTo('#files')
                                        goUpload = false
                                   }   
                              }
                              if(goUpload) {
                                   data.formData = params
                              } else {
                                   return false
                              }
                         },
                         add: function (e, data) {
                              data.context = $('<p/>').text('Subiendo...').appendTo('#files');
                              data.submit();
                         },
                         acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
                         disableImageResize: true,
                         maxFileSize: 5000000,
                    }
               )
               
               $('#cerrarFrm').button().click(
                    function() {
                         $('#up_div').fadeOut()
                         cargaFotos()
                    }
               )
               $(document).ajaxStop($.unblockUI)
               setTimeout("cargaFotos()", 500)
          }
     )
          
     function cargaFotos(){
          espera()
          $.post(
               '{% url "media_fondo" %}' + '/1', 
               '',
               function(data){
                   fotos(data, $('#FPul'))
               },
               'json'
          )
          $.post(
               '{% url "media_fondo" %}' + '/0', 
               '',
               function(data){
                   fotos(data, $('#Albm'))
               },
               'json'
          )
     }
     
     function fotos(datos, ctrl) {
          ctrl.empty()
          var dat = sortObject(datos)
          for (x in dat) {
               cur = dat[x]
               im =  '<li class="bordea ui-widget-content ui-corner-tr" id="img_' + cur.tipo + '_' + cur.id + '"><h5 class="ui-widget-header titulofoto"></h5><div class="imgcont"><img alt="' + cur.ds + '" src="'
               if (cur.thumb != '') {
                    im += cur.thumb
               } else {
                    im += cur.foto
               }
               im += '" width="100"/></div><a href="' + cur.foto + '" title="Ampliar" class="ui-icon ui-icon-zoomin">Ampliar</a>'
               im += '<span>' + cur.size[0] + 'x' + cur.size[1] + '</span>'
               if (ctrl.attr('id') != 'Albm') im += '<a href="#" title="Borrar" class="ui-icon ui-icon-trash" rel="' + cur.id + '">Borrar</a>'
               im += '</li>'
               var lis = $(im).appendTo(ctrl)
               if (ctrl.attr('id') == 'Albm') {
                    lis.draggable(
                         {
                              revert: 'invalid'
                         }
                    )
               }
          }
     }
     
     function espera() {
          $.blockUI({message: '<h3><img src="{{ STATIC_URL }}img/superbgloading.gif" style="vertical-align: middle; margin: 5px">Espere, por favor...</h3>'})
     }
     
     // image preview function, demonstrating the ui.dialog used as a modal window
     function viewLargerImage( $link ) {
          var src = $link.attr( 'href' ),
          title = $link.siblings( 'img' ).attr( 'alt' ),
          $modal = $( 'img.chopo[src$="' + src + '"]' )
          if ( $modal.length) {
               $modal.dialog( 'open' )
          } else {
               var img = $( '<img class="chopo" alt="' + title + '" style="display: none padding: 8px" />' )
                    .attr( 'src', src ).appendTo( 'body' )
               var ancho = parseInt($link.siblings('span').text().split('x')[0]) + 35
               setTimeout(function() {
                    img.dialog({
                         title: title,
                         modal: true,
                         minWidth: ancho,
                         positon: 'top',               
                         resizable: false
                    })
               }, 100 )
          }
     }

     function deleteImage($cual) {
          if (confirm('¿Excluir la imagen de la lista?')) {
               $.post(
                    '{% url "borraffon" %}', 
                    {'media_id':  $cual.attr('rel')}
               )
               cargaFotos()
          }         
     }
     
     function reordenar() {
          espera()
          var arr = $('#FPul').sortable('toArray')
          var n = 0
          for (x in arr) {
              $.post(
                    '{% url "ordenaffon" %}', 
                    {'media_id': arr[x].split('_')[2], 'orden': n}
               )
               n++               
          }
     }
     
     function nuevofondo(foto) {
          $.post(
               '{% url "mdm.views.nuevofon" %}',
               {'media_id': foto.attr('id').split('_')[2]}
               )
          cargaFotos()
     }
     
     function sortObject(o) {
         var sorted = {},
         key, a = [];

         for (key in o) {
             if (o.hasOwnProperty(key)) {
                     a.push(key);
             }
         }

         a.sort();

         for (key = 0; key < a.length; key++) {
             sorted[a[key]] = o[a[key]];
         }
         return sorted;
     }     
     </script>
{% endblock  %}
